﻿using com.tanlingyun.helper;
using com.tanlingyun.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Security.Principal;
using com.tanlingyun.baojia.Entity;
using com.tanlingyun.DbServices;

namespace com.tanlingyun.Baojia.Controllers
{
    
    public class BaseController : Controller
    {
        protected User entityUser = null;

        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            bool IsAuthorized = false;

            string userCookie = CookieHelper.GetValue(".user") as string;
            if (!string.IsNullOrWhiteSpace(userCookie))
            {
                userCookie = com.tanlingyun.helper.UtilityHelper.DecodeBase64(userCookie);
                string[] userArr = userCookie.Split(':');
                if (userArr != null && userArr.Length == 2)
                {
                    UserService _userService = new UserService();
                    OperateResult<User> result = _userService.ValidateUser(int.Parse(userArr[0]), userArr[1]);
                    if(result.code == ResultCode.Success)
                    {
                        IsAuthorized = true;

                        //IIdentity identity = new GenericIdentity(helper.JsonHelper.Serialize(result.data), result.data.level_type.ToString());
                        //IPrincipal principal = new GenericPrincipal(identity, new string[] { result.data.level_type.ToString() });
                        //System.Threading.Thread.CurrentPrincipal = principal;

                        entityUser = result.data;

                        //验证
                        UserTypeAttribute[] attr =  (UserTypeAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(UserTypeAttribute),true);
                        if(attr == null || attr.Length == 0)
                            attr = (UserTypeAttribute[])filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(UserTypeAttribute), true);
                        if(attr!=null && attr.Length > 0)
                        {
                            if (!attr.All(x => x.type.Contains<ELevelType>((ELevelType)result.data.level_type)))
                            {
                                filterContext.Result = HttpNotFound();
                            }
                        }
                    }
                }
            }
            if (!IsAuthorized)
            {
                if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false))
                {
                    base.OnAuthentication(filterContext);
                    return;
                }
                else
                {
                    filterContext.Result = RedirectToAction("SignIn", "User");
                }
            }
            base.OnAuthentication(filterContext);
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            try
            {
                Log log = new Log() { data = filterContext.Exception.Message, detail = filterContext.Exception.StackTrace, time = DateTime.Now, user_id = entityUser.id };
                BaseService _baseService = new BaseService();
                _baseService.AddLog(log);
            }
            catch
            {
                helper.LogHelper.SaveNote("Exception", filterContext.Exception.Message + Environment.NewLine + filterContext.Exception.StackTrace);
            }
            base.OnException(filterContext);
        }

        /// <summary>
        /// 返回错误
        /// </summary>
        /// <param name="code"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        protected JsonResult ErrorResult(ResultCode code,string error = "")
        {
            return Json(new { code = (int)code, ErrorMessage = error });
        }

        /// <summary>
        /// 成功结果
        /// </summary>
        /// <returns></returns>
        protected JsonResult SuccessResult()
        {
            return Json(new { code = (int)ResultCode.Success });
        }

        public JsonResult SuccessResult<T>(T data)
        {
            return Json(new { code = (int)ResultCode.Success, data = data });
        }

        protected JsonResult DataPageResult<T>(PageInfo<T> Page)
        {
            return Json(new { code = 0, total = Page.TotalCount, rows = Page.List, number = Page.PageIndex, size = Page.PageSize });
        }
    }

    /// <summary>
    /// 用户访问类型
    /// </summary>
    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,Inherited = true)]
    public class UserTypeAttribute:System.Attribute
    {
        public ViewModel.ELevelType[] type;    
    }
    
}